import { decryptAES, encryptAES, encryptMD5 } from '@/utils/secret'

// 数据传输签名算法
export function buildHeaderSign(url, userStore, param_json) {
  let headers = {
    'Content-Type': 'application/json; charset=utf-8', // 强制声明编码
  }
  if (url.includes('/App_Upload/')) {
    headers = {}
  }
  if (userStore.id && userStore.id != '') {
    // 密钥解密
    const app_key = decryptAES(userStore.app_key)
    const app_secret = decryptAES(userStore.app_secret)
    const access_token = decryptAES(userStore.access_token)

    headers.app_key = app_key
    headers.access_token = access_token
    headers.method = url
    headers.timestamp = Date.now()
    headers.version = '1.0'
    // 生成签名（强制 UTF-8 编码，MD5加密结果默认小写）
    const param_json_str = param_json && param_json != '' && Object.keys(param_json).length > 0 ? JSON.stringify(param_json) : ''
    // console.log(`${url}消息体参数：`, param_json_str)
    const paramPattern = app_secret + headers.app_key + headers.method + param_json_str + headers.timestamp + headers.version + app_secret
    // console.log(`${url}生成签名串：`, paramPattern)
    headers.sign = encryptMD5(paramPattern)
    // console.log(`${url}生成签名串：`, headers)
  }
  return headers
}

// 请求地址BaseUrl
export function getBaseURL() {
  const isProxyEnabled = import.meta.env.VITE_OPEN_PROXY.toString() === 'true'
  const baseUrl = import.meta.env.DEV && isProxyEnabled ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL
  return baseUrl
}
